package com.gpj.sqlbuilder.template;

import com.gpj.sqlbuilder.sysfun.SystemFunction;
import com.gpj.sqlbuilder.utils.ReflectUtil;
import com.gpj.sqlbuilder.utils.TextUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * @className FormatTemplate
 * @description TODO
 * @author GPJ
 * @date 2021/4/16 20:49
 * @version 1.0
 **/
public class FormatTemplate extends ElementTemplate{
	private static final String FORMAT_START_MARK = "<format>";
	private static final String FORMAT_TAIL_MARK = "</format>";

	private static final String ATTRIBUTE_KEY_FORMAT = "format";

	public FormatTemplate(int start, int tail, Template parent) {
		super(start, tail, parent);
	}

	@Override
	protected String getStartMark() {
		return FORMAT_START_MARK;
	}

	@Override
	protected String getTailMark() {
		return FORMAT_TAIL_MARK;
	}

	@Override
	protected void doBuild() {
		if (!children.isEmpty()) {
			for(Template child : children){
				child.build();
				sql.append(child.getSql());
			}
		}

		String format = getAttribute(ATTRIBUTE_KEY_FORMAT, "");
		if(StringUtils.isBlank(format)) return;

		format = TextUtils.roundValue("#[*]", format);

		sql = new StringBuffer((String) ReflectUtil.invoke(this, format));
	}

	private String whitoutLastComma(){
		int index = sql.lastIndexOf(",");
		return sql.substring(0, index) + sql.substring(index + 1);
	}
}
